/**
 * Created by Ding on 2016/4/8.
 * Copyright (c) 2016, auais.com All Rights Reserved.
 * File Name:
 * Package Name:
 * Date:2016/4/8 11:23
 */
const ObjectID = require('mongodb').ObjectID;
const mongo = require('mongodb');
//const GridStore = require('mongodb').GridStore;
const GridFSBucket = require('mongodb').GridFSBucket;
const fs = require("fs");
const path = require('path');
const Grid = require('gridfs-stream');
const Busboy = require('busboy');
const inspect = require('util').inspect;
const gm = require("gm");
module.exports = {
    open:false,
    description:'信息上传',
    handler: (req, res, next)=>{
        req.context=req.context||{};
        console.log('req.context:::',req.context);
        const userId=req.context.user||new ObjectID(0);
        const compress=req.query.compress;
        const versionNum = req.query.version||'';
        const gfs = Grid(req.mongo, mongo);
        const busboy = new Busboy({headers: req.headers});
        //第三方中间件接收上传
        req.pipe(busboy);
        busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
            var ext = path.extname(filename).toLowerCase();
            var filesize = 0;
            const id = new ObjectID();
            //微信录音，修改content_type 为 audio/mp4
            if(ext===".mp3"&& filename.toLowerCase().substr(0,4)==="tmp_")
                mimetype="audio/mp4";
            const writestream = gfs.createWriteStream({
                _id: id,
                mode: "w",
                filename: filename,
                content_type: mimetype
            });
            //file.pipe(writestream);
            console.log('mimetype',mimetype);
            if (mimetype.indexOf("image/") != -1 && compress=="true") {
                console.log("压缩中 ……");
                gm(file).resize('640', '640').stream().pipe(writestream);
            } else {
                file.pipe(writestream);
            }

            file.on('end', function () {
                //console.log("end");
                // const url = "/res/" + id+"/content";
                const url = req.config.sys.resHost + "/res/" + id+"/content";

                const fileObj = {
                    id: id,
                    filename: filename,
                    content_type: mimetype,
                    filesize: filesize,
                    url: url
                };
                // res.json(fileObj);
                res.reply({code:0,message:"上传成功",data:fileObj});
                //将资源记录用户表
                var fn = function () {
                };

                    if ([".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
                            ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid"].indexOf(ext)>=0) {
                        req.mongo.collection("userMedia").updateOne({_id: userId}, {$push: {"videos": {_id:id,"uploadTime":new Date(),"url":url}}},{upsert:true}, fn);
                    } else if ([".png", ".jpg", ".jpeg", ".gif", ".bmp"].indexOf(ext)>=0) {
                        req.mongo.collection("userMedia").updateOne({_id: userId}, {$push: {"images": {_id:id,"uploadTime":new Date(),"url":url}}},{upsert:true}, fn);
                    }else if ([".apk"].indexOf(ext)>=0) {
                        req.mongo.collection("apkFile").insert({
                            _id: id,
                            "userId": userId,
                            "version": versionNum,
                            filename: fileObj.filename,
                            "url":url,
                            "uploadTime": new Date()
                        }, fn);
                    }
                    else if  ([".exe"].indexOf(ext)>=0) {
                        req.mongo.collection("exeFile").insert({
                            _id: id,
                            "userId": userId,
                            "version": versionNum,
                            filename: fileObj.filename,
                            "url": url,
                            "uploadTime": new Date()
                        }, fn);
                    } else {
                        req.mongo.collection("userMedia").updateOne({_id: userId}, {$push: {"files": {_id:id,"uploadTime":new Date(),"url":url}} },{upsert:true}, fn);
                    }

            }).on('error', function (err) {
                console.log("err:" + err)
            }).on('data', function (data) {
                filesize += data.length;
                //   console.log(filesize);
            });

        })
    }
};